<template>
  <div id="centerDiv" class="mapcontainer">
    <div id="streetScape-container" v-if="showStreetScape">
      <iframe id="streeScape" class="stree" :src="baiduHtmlPath"> </iframe>
    </div>
    <Map :url="configUrl" @onload="onMapload" />
  </div>
</template>

<script>
import Map from '../components/mars3d/Map.vue'
import Fps from './fps'

export default {
  name: 'Index',

  components: {
    Map
  },

  data() {
    const basePathUrl = window.basePathUrl || ''
    return {
      configUrl: basePathUrl + 'config/config.json',
      showStreetScape: false,
      arrColor: ['rgb(15,176,255)', 'rgb(18,76,154)', '#40C4E4', '#42B2BE', 'rgb(51,176,204)', '#8CB7E5', 'rgb(0,244,188)', '#139FF0'],
      index: 0,
      rotation: 0
    }
  },
  mounted() {
    this.$bus.$on('updateShowStreetScape', this.updateShowStreetScape)
    window.dynamicChangeMSSE = this.dynamicChangeMSSE
  },
  beforeDestroy() {
    this.$bus.$off('updateShowStreetScape') // 记得写上销毁事件的名称 不然会全部销毁
  },
  computed: {
    baiduHtmlPath() {
      // this.map == null ? 'html/baidu.html?lng=106.583149&lat=29.582056' :
      var path = 'html/baidu.html?lng=' + this.map.getCenter().lng + '&lat=' + this.map.getCenter().lat

      return path
    }
  },
  methods: {
    updateShowStreetScape(target) {
      this.showStreetScape = target
      if (target) {
        this.goSplitScreen()
      }
    },
    goSplitScreen() {
      this.$nextTick(() => {
        this.splitScreen()
      })
    },
    splitScreen() {
      const domStreetScape = document.getElementById('streetScape-container')
      const dom3d = document.getElementById('mars3d-container')

      domStreetScape.style.width = '50%'
      dom3d.style.width = '50%'
      dom3d.style.left = '50%'
      domStreetScape.style.display = 'block'
      dom3d.style.display = 'block'
    },

    // 地图构造完成回调
    onMapload(map) {
      this.rotation = this.Cesium.Math.toRadians(50)
      // 加载建筑白膜
      this.loadBuildingsLayer(map)
      this.loadEffects(map)
      // 加载高德poi
      // this.loadGeodePoiLayer(map)

      // 以下为演示代码
      // 创建entity图层
      // const graphicLayer = new this.mars3d.layer.GraphicLayer()
      // map.addLayer(graphicLayer)

      // // 2.在layer上绑定监听事件
      // graphicLayer.on(this.mars3d.EventType.click, function (event) {
      //   console.log('监听layer，单击了矢量对象', event)
      // })
      // graphicLayer.on(this.mars3d.EventType.mouseOver, function (event) {
      //   console.log('监听layer，鼠标移入了矢量对象', event)
      // })
      // graphicLayer.on(this.mars3d.EventType.mouseOut, function (event) {
      //   console.log('监听layer，鼠标移出了矢量对象', event)
      // })

      // // 可在图层上绑定popup,对所有加到这个图层的矢量数据都生效
      // graphicLayer.bindPopup('我是layer上绑定的Popup', {
      //   anchor: [0, -10]
      // })

      // // 可在图层绑定右键菜单,对所有加到这个图层的矢量数据都生效
      // graphicLayer.bindContextMenu([
      //   {
      //     text: '删除对象',
      //     iconCls: 'fa fa-trash-o',
      //     callback: function (e) {
      //       const graphic = e.graphic
      //       if (graphic) {
      //         graphicLayer.removeGraphic(graphic)
      //       }
      //     }
      //   }
      // ])

      // 加一些演示数据
      // this.addGraphic_e01(graphicLayer)
      // this.addGraphic_e02(graphicLayer)
      // this.addGraphic_e03(graphicLayer)
      // this.addGraphic_e04(graphicLayer)
      // this.addGraphic_e05(graphicLayer)
      // this.addGraphic_e06(graphicLayer)
      // this.addGraphic_e07(graphicLayer)
      // this.addGraphic_e08(graphicLayer)
      // this.addGraphic_e09(graphicLayer)
      // this.addGraphic_e10(graphicLayer)
      // this.addGraphic_e11(graphicLayer)
      // this.addGraphic_e12(graphicLayer)
      // this.addGraphic_e13(graphicLayer)
      // this.addGraphic_e14(graphicLayer)
      // this.addGraphic_e15(graphicLayer)
    },

    loadBuildingsLayer(map) {
      map.scene.light = new this.Cesium.DirectionalLight({
        direction: map.scene.camera.direction
      })

      map.on(this.mars3d.EventType.cameraMoveEnd, function (event) {
        map.scene.light.direction = map.scene.camera.direction
      })
      const bloomEffect = new this.mars3d.effect.BloomEffect({
        enabled: false
      })
      map.addEffect(bloomEffect)

      // 自定义特效 Shader
      const fragmentShader = `
          // 注意shader中写浮点数是，一定要带小数点，否则会报错，比如0需要写成0.0，1要写成1.0
          float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
          float _heightRange = 80.0; // 高亮的范围(_baseHeight ~ _baseHeight + _heightRange)
          float _glowRange = 100.0; // 光环的移动范围(高度)

          // 建筑基础色
          float mars_height = marsJzwHeight - _baseHeight+60.0;
          float mars_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
          float mars_a12 = mars_height / _heightRange + sin(mars_a11) * 0.1;
          gl_FragColor *= vec4(vec3(mars_a12), 1.0);// 渐变

          // 动态光环
          float time = fract(czm_frameNumber / 360.0);
          time = abs(time - 0.5) * 2.0;
          float mars_h = clamp(mars_height / _glowRange, 0.0, 1.0);
          float mars_diff = step(0.005, abs(mars_h - time));
          gl_FragColor.rgb += gl_FragColor.rgb * (1.0 - mars_diff);
       `

      const tilesetLayer = new this.mars3d.layer.TilesetLayer({
        url: '//' + this.dataServerUrl + '/3dtiles/CQBuildings/tileset.json',
        style: new this.Cesium.Cesium3DTileStyle({
          color: {
            conditions: [['true', 'color("#4B61E1")']]
          }
        }),
        maximumScreenSpaceError: 16,
        maximumMemoryUsage: 3026,
        marsJzwStyle: fragmentShader,
        skipLevelOfDetail: true,
        preferLeaves: false,
        popup: 'all'
      })
      this.map.tilesetLayer = tilesetLayer
      map.addLayer(tilesetLayer)

      Fps.loop()
    },
    loadEffects(map) {
      // 模型的中心点
      const position = [106.573363, 29.560139, 0] // 用于围绕旋转 + 中心点扩散 + 旋转的图片
      const center = this.Cesium.Cartesian3.fromDegrees(position[0], position[1], 70) // 用于div标注和远眺的线
      // 中心扩散点
      const circleDiffuseWallGlow = new this.mars3d.graphic.DiffuseWall({
        name: '中心扩散点',
        position: position,
        style: {
          diffHeight: 500, // 高度
          radius: 150, // 半径
          color: '#7ffeff',
          speed: 6 // 速度
        }
      })
      map.graphicLayer.addGraphic(circleDiffuseWallGlow)

      // divgraphic标注
      const divgraphic = new this.mars3d.graphic.DivGraphic({
        position: center,
        style: {
          html: `<div class="marsBlackPanel">
                <div class="marsBlackPanel-text">解放碑商圈</div>
            </div>`,
          horizontalOrigin: this.Cesium.HorizontalOrigin.LEFT, // 横向定位
          verticalOrigin: this.Cesium.VerticalOrigin.CENTER // 垂直定位
        }
      })
      map.graphicLayer.addGraphic(divgraphic)

      // 扫描圆形
      const scanCircle = new this.mars3d.graphic.CircleEntity({
        position: this.Cesium.Cartesian3.fromDegrees(106.569611, 29.55599, 24.2),
        style: {
          radius: 240.0,
          material: this.mars3d.MaterialUtil.createMaterialProperty(this.mars3d.MaterialType.CircleScan, {
            image: 'img/textures/circleScan.png',
            color: '#ffffff'
          }),
          stRotation: new this.Cesium.CallbackProperty(this.getRotationValue, false),
          classificationType: this.Cesium.ClassificationType.BOTH,
          clampToGround: true
        }
      })
      map.graphicLayer.addGraphic(scanCircle)
    },

    getRotationValue() {
      this.rotation -= 0.007
      return this.rotation
    },
    dynamicChangeMSSE(isIncrease) {
      if (isIncrease) {
        this.map.tilesetLayer.options.maximumScreenSpaceError = this.map.tilesetLayer.options.maximumScreenSpaceError * 2 >= 16 ? 16 : this.map.tilesetLayer.options.maximumScreenSpaceError * 2
      } else {
        if (this.map.tilesetLayer.options.maximumScreenSpaceError !== 1) {
          this.map.tilesetLayer.options.maximumScreenSpaceError = this.map.tilesetLayer.options.maximumScreenSpaceError - 1
        }
      }
    },
    loadGeodePoiLayer(map) {
      // 高德POI图层，演示大数据的分块加载

      const layer = new this.mars3d.layer.GeodePoiLayer({
        minimumLevel: 13,
        debuggerTileInfo: false, // 是否显示网格信息（测试用）
        key: this.mars3d.Token.gaodeArr, // 在实际项目中将下面高德KEY换为自己申请的，因为该key不保证长期有效。
        filter: {
          types: '120000|130000|190000'
        },
        height: 5,
        symbol: {
          styleOptions: {
            image: 'img/marker/mark3.png',
            scale: 0.7,
            scaleByDistance: true,
            scaleByDistance_far: 20000,
            scaleByDistance_farValue: 0.5,
            scaleByDistance_near: 1000,
            scaleByDistance_nearValue: 1,
            label: {
              text: '{name}',
              font_size: 15,
              color: '#ffffff',
              outline: true,
              outlineColor: '#000000',
              pixelOffsetY: -30,
              distanceDisplayCondition: true,
              distanceDisplayCondition_far: 4000,
              distanceDisplayCondition_near: 0
            }
          }
        },
        // 当是entity类型时，点的聚合配置
        clustering: {
          enabled: true,
          pixelRange: 20
        }
      })
      map.addLayer(layer)
    },
    loadCommunity(map) {
      const geoJsonLayer = new this.mars3d.layer.GeoJsonLayer({
        name: '省界线',
        url: '//localhost/geojson/北碚区_百度小区、商场 (V1.0).json',
        symbol: {
          // 可以通过配置symbol参数来指定渲染的矢量数据类型和样式。
          type: 'polygon',
          styleOptions: {
            materialType: this.mars3d.MaterialType.PolyGradient, // 重要参数，指定材质
            color: '#3388cc',
            opacity: 0.7,
            alphaPower: 1.3
          }
          // callback: function (attr, styleOpt) {
          //   return {
          //     color: that.getColor()
          //   }
          // }
        }
      })
      map.addLayer(geoJsonLayer)
    },
    getColor() {
      return this.arrColor[++this.index % this.arrColor.length]
    },
    // 以下为演示代码
    addGraphic_e01(graphicLayer) {
      const graphic = new this.mars3d.graphic.LabelEntity({
        position: new this.mars3d.LatLngPoint(116.1, 31.0, 1000),
        style: {
          text: 'Mars3D平台',
          font_size: 25,
          font_family: '楷体',
          color: '#003da6',
          outline: true,
          outlineColor: '#bfbfbf',
          outlineWidth: 2,
          horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
          visibleDepth: false
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e02(graphicLayer) {
      const graphic = new this.mars3d.graphic.PointEntity({
        position: [116.2, 31.0, 1000],
        style: {
          color: '#ff0000',
          pixelSize: 10,
          outline: true,
          outlineColor: '#ffffff',
          outlineWidth: 2
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e03(graphicLayer) {
      const graphic = new this.mars3d.graphic.BillboardEntity({
        name: '贴地图标',
        position: [116.3, 31.0, 1000],
        style: {
          image: 'http://mars3d.cn/example/img/marker/mark2.png',
          scale: 1,
          horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e04(graphicLayer) {
      const graphic = new this.mars3d.graphic.PlaneEntity({
        position: new this.mars3d.LatLngPoint(116.4, 31.0, 1000),
        style: {
          plane: new this.Cesium.Plane(this.Cesium.Cartesian3.UNIT_Z, 0.0),
          dimensions: new this.Cesium.Cartesian2(4000.0, 4000.0),
          material: this.mars3d.MaterialUtil.createMaterialProperty(this.mars3d.MaterialType.Image, {
            image: 'http://mars3d.cn/example/img/textures/movingRiver.png',
            transparent: true
          })
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    //
    addGraphic_e05(graphicLayer) {
      const graphic = new this.mars3d.graphic.BoxEntity({
        position: new this.mars3d.LatLngPoint(116.5, 31.0, 1000),
        style: {
          dimensions: new this.Cesium.Cartesian3(2000.0, 2000.0, 2000.0),
          fill: true,
          color: '#00ffff',
          opacity: 0.9,
          heading: 45,
          roll: 45,
          pitch: 0
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e06(graphicLayer) {
      const graphic = new this.mars3d.graphic.CircleEntity({
        position: [116.1, 30.9, 1000],
        style: {
          radius: 1800.0,
          color: '#00ff00',
          opacity: 0.3,
          outline: true,
          outlineWidth: 3,
          outlineColor: '#ffffff',
          clampToGround: true
        },
        popup: '直接传参的popup'
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e07(graphicLayer) {
      const graphic = new this.mars3d.graphic.CylinderEntity({
        position: [116.2, 30.9, 1000],
        style: {
          length: 3000.0,
          topRadius: 0.0,
          bottomRadius: 1300.0,
          color: '#00FFFF',
          opacity: 0.7
        },
        popup: '直接传参的popup'
      })
      graphicLayer.addGraphic(graphic)
    },

    //
    addGraphic_e08(graphicLayer) {
      const graphic = new this.mars3d.graphic.EllipsoidEntity({
        position: new this.mars3d.LatLngPoint(116.3, 30.9, 1000),
        style: {
          radii: new this.Cesium.Cartesian3(1500.0, 1500.0, 1500.0),
          material: this.Cesium.Color.RED.withAlpha(0.5),
          outline: true,
          outlineColor: this.Cesium.Color.WHITE.withAlpha(0.3)
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e09(graphicLayer) {
      const graphic = new this.mars3d.graphic.ModelEntity({
        name: '消防员',
        position: [116.4, 30.9, 1000],
        style: {
          url: 'http://data.mars3d.cn/gltf/mars/firedrill/xiaofangyuan-run.gltf',
          scale: 16,
          minimumPixelSize: 100
        }
      })
      graphicLayer.addGraphic(graphic)
    },

    addGraphic_e10(graphicLayer) {
      const graphic = new this.mars3d.graphic.PolylineEntity({
        positions: [
          [116.5, 30.9, 1000],
          [116.52, 30.91, 1000],
          [116.53, 30.89, 1000]
        ],
        style: {
          width: 5,
          color: '#3388ff'
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    },

    addGraphic_e11(graphicLayer) {
      const graphic = new this.mars3d.graphic.PolylineVolumeEntity({
        positions: [
          [116.1, 30.8, 1000],
          [116.12, 30.81, 1000],
          [116.13, 30.79, 1000]
        ],
        style: {
          shape: 'pipeline',
          radius: 80,
          color: '#3388ff',
          opacity: 0.9
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    },

    addGraphic_e12(graphicLayer) {
      const graphic = new this.mars3d.graphic.CorridorEntity({
        positions: [
          [116.2, 30.8, 1000],
          [116.22, 30.81, 1000],
          [116.23, 30.79, 1000],
          [116.247328, 30.806077, 610.41]
        ],
        style: {
          width: 500,
          color: '#3388ff'
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    },

    addGraphic_e13(graphicLayer) {
      const graphic = new this.mars3d.graphic.WallEntity({
        positions: [
          [116.3, 30.8, 1000],
          [116.31, 30.81, 1000],
          [116.334639, 30.800735, 721.39],
          [116.32, 30.79, 1000]
        ],
        style: {
          closure: true,
          diffHeight: 500,
          // 动画线材质
          material: this.mars3d.MaterialUtil.createMaterialProperty(this.mars3d.MaterialType.LineFlow, {
            image: 'http://mars3d.cn/example/img/textures/fence.png',
            color: '#00ff00',
            speed: 10,
            axisY: true
          })
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    },

    addGraphic_e14(graphicLayer) {
      const graphic = new this.mars3d.graphic.RectangleEntity({
        positions: [
          [116.383144, 30.819978, 444.42],

          [116.42216, 30.793431, 1048.07]
        ],
        style: {
          color: '#3388ff',
          opacity: 0.5,
          outline: true,
          outlineWidth: 3,
          outlineColor: '#ffffff'
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    },

    addGraphic_e15(graphicLayer) {
      const graphic = new this.mars3d.graphic.PolygonEntity({
        positions: [
          [116.510278, 30.834372, 567.29],
          [116.530085, 30.809331, 448.31],
          [116.507367, 30.788551, 98.21],
          [116.472468, 30.823091, 677.39]
        ],
        style: {
          material: this.mars3d.MaterialUtil.createMaterialProperty(this.mars3d.MaterialType.Water, {
            normalMap: 'http://mars3d.cn/example/img/textures/waterNormals.jpg', // 水正常扰动的法线图
            frequency: 8000.0, // 控制波数的数字。
            animationSpeed: 0.02, // 控制水的动画速度的数字。
            amplitude: 5.0, // 控制水波振幅的数字。
            specularIntensity: 0.8, // 控制镜面反射强度的数字。
            baseWaterColor: '#006ab4', // rgba颜色对象基础颜色的水。#00ffff,#00baff,#006ab4
            blendColor: '#006ab4' // 从水中混合到非水域时使用的rgba颜色对象。
          })
        }
      })
      graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    }
  }
}
</script>

<style>
.mapcontainer {
  position: relative;
  height: 100%;
  overflow: hidden;
}

#streetScape-container {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

/* 街景css */
.stree {
  width: 100%;
  height: 100%;
  overflow: hidden;
  margin: 0;
}
.streetimg {
  position: absolute;
  right: 10px;
  top: 10px;
  height: 82px;
  width: 60px;
  background-color: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(128, 128, 128, 0.5);
  box-shadow: 0 3px 14px rgba(128, 128, 128, 0.5);
}
.streetimg .text {
  display: block;
  margin-top: 48px;
  margin-left: 18px;
}
</style>
